package com.kdweibo.demo.activities;

import java.util.List;

import kdweibo4j.Network;
import kdweibo4j.User;
import kdweibo4j.Weibo;
import kdweibo4j.WeiboException;
import kdweibo4j.http.AccessToken;



import com.kdweibo.demo.activities.AuthConstant;

/**
 * 使用用户名，密码的XAuth登录方式
 */
public class TestXAuth {
	public final static String TAG = "ACT_XAuth";
	private User loginUser;
	private AccessToken accessToken;

	/**
	 * XAuth 认证获取AccessToken
	 * @throws WeiboException
	 */
	private void doLogin() throws WeiboException {
		String username = "xxx@xxx.cn";
		String password = "xxxxxxxxxx";
		
		Weibo weibo = AuthConstant.getInstance().getWeibo();
		weibo.setOAuthAccessToken(null);
		weibo.setOAuthConsumer(Weibo.CONSUMER_KEY, Weibo.CONSUMER_SECRET);
		accessToken = weibo.getXAuthAccessToken(username, password,
				"client_auth");
		if (accessToken != null && accessToken.getToken() != null
				&& accessToken.getTokenSecret() != null) {
			loginUser = weibo.verifyCredentials();
		} else {
			accessToken = null;
			throw new WeiboException("ACT_CAuth, doLogin using XAuth catch error，accessToken is null", -1);
		}
	}


	/**
	 * 获取我加入的网络（社区列表）
	 * @throws WeiboException
	 */
	protected void getNetWorkList() throws WeiboException {
		Weibo weibo = AuthConstant.getInstance().getWeibo();
		List<Network> myNetwork = weibo.getMyNetworks(null);
		for(int i=0;i<myNetwork.size();i++){
			System.out.println("["+(i+1)+"]: "+myNetwork.get(i));
		}
	}
	
	/**
	 * AccessToken token: 9412d5987c9263e467b7b84be5927bc5
	 * AccessToken tokenSecret: edcbc5a31782c25a7a86c0b72860829a
	 * @param args
	 */
	public static void main(String[] args) {
		TestXAuth xauth = new TestXAuth();
		try {
			xauth.doLogin();
			System.out.println("loginUser id: "+xauth.loginUser.id);
			System.out.println("loginUser name: "+xauth.loginUser.screenName);
			System.out.println("AccessToken token:"+xauth.accessToken.getToken());
			System.out.println("AccessToken tokenSecret:"+xauth.accessToken.getTokenSecret());
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			xauth.getNetWorkList();
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}